<template>
  <el-dialog
    :visible.sync="addProjectDialog"
    width="80%"
    :destroy-on-close="true"
    :before-close="handleClose">
    <el-row>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-col :span="12">
          <el-card class="box-card">
            <div slot="header">
              <span>项目信息</span>
            </div>
            <div class="text item">
                <el-form-item label="公司名称" prop="companyName">
                  <el-input v-model="form.companyName" :disabled="isEdit"></el-input>
                </el-form-item>
                <el-form-item label="项目名称" prop="applicationName">
                  <el-input v-model="form.applicationName" :disabled="isEdit"></el-input>
                </el-form-item>
                <el-form-item label="logo">
                  <el-upload
                    action="/api/v1/upload"
                    list-type="picture-card"
                    :limit="1"
                    :disabled="isEdit"
                    :file-list="logoList"
                    accept=".png,.jpg"
                    :on-preview="handlePictureCardPreview"
                    :on-success="handleSuccess"
                    :on-exceed="handleExceed"
                    :on-remove="handleRemove">
                    <i class="el-icon-plus"></i>
                  </el-upload>
                  <el-dialog class="pictureDialog" :visible.sync="dialogVisible" :append-to-body="true">
                    <img width="100%" :src="dialogImageUrl" alt="">
                  </el-dialog>
                </el-form-item>
                <el-form-item label="展示图">
                  <el-upload
                    action="/api/v1/upload"
                    list-type="picture-card"
                    :limit="1"
                    :disabled="isEdit"
                    :file-list="loginList"
                    :on-preview="handlePictureCardPreview"
                    :on-success="loginPictureSuccess"
                    :on-exceed="handleExceed"
                    :on-remove="loginPictureRemove">
                    <i class="el-icon-plus"></i>
                  </el-upload>
                  <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                  </el-dialog>
                </el-form-item>
                <el-form-item label="发布地址" prop="applicationUrl">
                  <el-input v-model="form.applicationUrl" :disabled="isEdit"></el-input>
                </el-form-item>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12" class="rightCard">
          <el-card class="box-card managerUser">
            <div slot="header">
              <span>管理账号</span>
            </div>
            <div class="text item">
                <el-form-item label="手机号" prop="username">
                  <el-input v-model="form.username" :disabled="isEdit" ></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password" v-show="psdIsShow">
                  <el-input v-model="form.password" show-password></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="repeatPassword" v-show="psdIsShow">
                  <el-input v-model="form.repeatPassword" show-password></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email" :disabled="isEdit">
                  <el-input v-model="form.email"></el-input>
                </el-form-item>
            </div>
          </el-card>
        </el-col>
      </el-form>
    </el-row>
    <span slot="footer" class="dialog-footer">
    <el-button @click="handleClose">取 消</el-button>
    <el-button type="primary" v-show="psdIsShow" @click="submitProject('form')">确 定</el-button>
  </span>
  </el-dialog>
</template>

<script>
  export default {
    props: ["addProjectDialog", "dialogData", "isEdit"],
    name: "addProject",

    data() {
      const validatePassword = (rule, value, callback) => {
        if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/.test(value)) {
          callback(new Error("请输入6-16位以内的数字字母组合!"));
        }
        callback();
      };
      const validateCheckPsd = (rule, value, callback) => {
        if (value === undefined || value === "") {
          callback(new Error("请再次输入密码"));
        } else {
          if (value !== this.form.password) {
            callback(new Error("两次输入密码不一致"));
          }
          callback();
        }
      };
      const validatePhone = (rule, value, callback) => {
        if (value === undefined) {
          callback(new Error("请输入手机号"));
        } else {
          if (
                  !/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/.test(
                          value
                  )
          ) {
            callback(new Error("请输入正确的手机号"));
          }
          callback();
        }
      };
      const validateEmail = (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入邮箱"));
        } else {
          if (
                  !/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(
                          value
                  )
          ) {
            callback(new Error("请输入正确的邮箱"));
          }
          callback();
        }
      };
      const validateCompanyName = (rule, value, callback) => {
        console.log(value)
        var patrn = /[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]/im;
        if (value === "" || !value) {
          callback(new Error("请输入公司名称"));
        } else {
          if (
                  patrn.test(
                          value
                  )
          ) {
            callback(new Error("公司名称不能包含特殊字符"));
          }
          callback();
        }
      };
      return {
        logoList: [],
        loginList: [],
        form: {
          logo: "",
          loginPicture: ""
        },
        dialogImageUrl: '',
        dialogVisible: false,
        rules: {
          companyName: [
            { required: true, validator: validateCompanyName, trigger: 'blur' }
          ],
          applicationName: [
            { required: true, message: '请输入项目名称', trigger: 'blur' }
          ],
          applicationUrl: [],
          username: [
            { required: true, validator: validatePhone, trigger: 'blur' }
          ],
          password: [
            { required: true, validator: validatePassword, trigger: 'blur' }
          ],
          repeatPassword: [
            { required: true, validator: validateCheckPsd, trigger: 'blur' }
          ],
          email: [
            { required: true, validator: validateEmail, trigger: 'blur' }
          ]
        },
        psdIsShow: true
      }
    },
    created() {
      if (this.isEdit) {
        this.form = this.dialogData;
        this.psdIsShow = false;
        if (this.dialogData.logo) {
          this.logoList.push({url: this.dialogData.logo})
        } else {
          this.logoList = [];
        }
        if (this.dialogData.loginPicture) {
          this.loginList.push({url: this.dialogData.loginPicture})
        } else {
          this.loginList = [];
        }
      } else {
        this.psdIsShow = true;
        this.form = {
          logo: "",
          loginPicture: ""
        };
        this.loginList = [];
        this.logoList = [];
      }
    },
    methods: {
      //模态框关闭
      handleClose() {
        this.$emit("getDialogStatus")
      },
      //提交
      submitProject(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.$post(`/v1/manage/project`, this.form).then(res => {
              console.log(res)
              if (res.data.code === 200) {
                this.$message.success(res.data.message);
                this.$emit("getDialogStatus", "reload")
              } else {
                this.$message.error("创建失败，请稍后再试！");
              }
            })
          }
        })
      },
      //文件上传成功
      handleSuccess(res) {
        if (res.code === 200) {
          this.$message.success("上传成功!");
          this.form.logo = res.data.img_url;
        } else {
          this.$message.error("上传失败，请重新上传!")
        }
      },
      loginPictureSuccess(res) {
        if (res.code === 200) {
          this.$message.success("上传成功!");
          this.form.loginPicture = res.data.img_url;
        } else {
          this.$message.error("上传失败，请重新上传!")
        }
      },
      //文件超出个数限制
      handleExceed() {
        this.$message.error("最多上传一张图片！")
      },
      //删除文件
      handleRemove() {
        this.form.logo = "";
      },
      loginPictureRemove() {
        this.form.loginPicture = "";
      },
      //查看文件
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      }
    }
  }
</script>

<style scoped lang="scss">
/deep/.el-dialog__footer {
  text-align: center;
}
  .rightCard {
    position: absolute;
    right: 0;
    height: 100%;
  }
  .managerUser {
    height: 100%;
  }
  .pictureDialog {
    z-index: 9999 !important;
  }
</style>
